package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.app.func.MyAllWindowFunction;
import com.atguigu.bean.TradePaySucBean;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.MyClickHouseUtil;
import com.atguigu.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

public class Dws0205TradePaySucWindow {
    public static void main(String[] args) throws Exception {
        //1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
//        tableEnv.getConfig().setIdleStateRetention(Duration.ofSeconds(18*60+5));
        //  状态后端设置
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");
        //2.从kafka dwd层读取dwd_trade_pay_detail_suc的数据
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_trade_pay_detail_suc", "pay_suc"), WatermarkStrategy.noWatermarks(), "kafka-source");
        //3.将数据转换为JSONOBJECT,并按照uid keyby
        KeyedStream<JSONObject, String> keyedUidDS = kafkaDS.map(JSON::parseObject).keyBy(r -> r.getString("user_id"));
        //4.将数据转换为JavaBean
        SingleOutputStreamOperator<TradePaySucBean> TradePaySucDS = keyedUidDS.map(new RichMapFunction<JSONObject, TradePaySucBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1)).build();
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("uid-state", String.class);
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public TradePaySucBean map(JSONObject jsonObject) throws Exception {
                String lastDt = valueState.value();
                Long ts = jsonObject.getLong("ts");
                String curDt = DateFormatUtil.toDate(ts);
                long paySucUcount = 0L;
                if (lastDt == null || !lastDt.equals(curDt)) {
                    valueState.update(curDt);
                    paySucUcount = 1L;

                }

                return new TradePaySucBean("", "", paySucUcount, jsonObject.getLong("callback_time"));
            }
        });
        //5.提取watermark
        SingleOutputStreamOperator<TradePaySucBean> TradePaySucWithWMDS = TradePaySucDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TradePaySucBean>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<TradePaySucBean>() {
            @Override
            public long extractTimestamp(TradePaySucBean tradePaySucBean, long l) {
                return tradePaySucBean.getTs();
            }
        }));

        //5.开窗 聚合
        SingleOutputStreamOperator<TradePaySucBean> reduceDS = TradePaySucWithWMDS.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<TradePaySucBean>() {
            @Override
            public TradePaySucBean reduce(TradePaySucBean tradePaySucBean, TradePaySucBean t1) throws Exception {
                tradePaySucBean.setPaySucUcount(tradePaySucBean.getPaySucUcount() + t1.getPaySucUcount());
                return tradePaySucBean;
            }
        }, new MyAllWindowFunction<TradePaySucBean, TimeWindow>());
        //6.写出
        reduceDS.print("reduceDS>>>");
        reduceDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_trade_pay_suc_window values(?,?,?,?)"));
        env.execute();



    }

}
